import { FC, useState, MouseEvent, ChangeEvent, ReactNode } from "react";
import { FileInput, RemarkReplyHandleVessel, RemarkReplyUpdateVessel, ResouceAddHandleTitle, ResouceAddVessel, ResouceAddWhiteSpace, StatText, StatVessel, StatusDesc, StatusDescInfo, StatusVessel, StepsVessel, TitleHandle, TitleVessel, Vessel } from "./css";
import { Button, Drawer, Empty, Input, Modal, Select, Steps, Switch, Table, TableProps, Tooltip, message } from "antd";
import { ToTopOutlined, PaperClipOutlined, CheckOutlined, MinusOutlined } from "@ant-design/icons"
import * as XLSX from 'xlsx'
import { ResourceParam, addRemarkInfo, bacthSendSms, removeRemarkInfo, resouceAdd, resouceQuery, updateRemarkInfo, updateSendStatus, uploadRouce } from "../../service/resouce";
import { AxiosError } from "axios";



const { TextArea } = Input;

interface RemarkReply {
  id: number,
  resource_id: number,
  type: number,
  content: string,
  time: string,
  created_at?: string,
  updated_at?: string,
  created_id?: number,
  updated_id?: number,
  title?: string,
  description?: string
}


interface ResourceBody {
  company: string,
  corp_name: string,
  phone: string,
  email?: string,
}

interface Resource {
  id: number,
  link?: string,
  short_link?: string,
  company: string,
  corp_name: string,
  phone: string,
  email?: string,
  link_up?: number,
  is_link_up?: number,
  phone_send?: number,
  is_phone_send?: number,
  email_send?: number,
  is_email_send?: number,
  click_count?: number,
  is_exception?: number,
  created_at?: string,
  created_id?: number,
  updated_at?: string,
  updated_id?: number,
  remarkReplys?: RemarkReply[]
}

interface Screen {
  value: number
  label: string
}


interface RemarkReplyUpdate {
  id: number,
  title: string,
  description?: ReactNode,
  content: string
}

const Resouce: FC = () => {
  const [source, setSource] = useState<Resource[]>([])
  const [total, setTotal] = useState<number>(0)
  const [isShowAddRemark, setIsShowAddRemark] = useState<boolean>(false)
  //添加备注信息
  function addRemark(id: number) {
    setIsShowAddRemark(true)
    setAddRemarkId(id)
  }

  //点击查看备注
  function queryRemarkReplys(list: RemarkReply[] | undefined, type: number) {
    //过滤出备注信息列表
    let remarkReplys: RemarkReply[] = []
    if (list) {
      remarkReplys = list.filter(ele => ele.type === type)
    }
    //处理一下需要显示的内容
    remarkReplys = remarkReplys.map(ele => {
      return { ...ele, title: ele.time, description: ele.content }
    })

    Modal.info({
      title: '查看沟通备注',
      content: (
        <StepsVessel>
          {
            remarkReplys.length > 0 ? <Steps
              progressDot
              current={remarkReplys.length}
              direction="vertical"
              items={remarkReplys}
            /> : <Empty style={{
              marginLeft: '-30px'
            }} description={type === 0 ? "暂无备注" : "暂无回复"} />
          }
        </StepsVessel>
      ),
      okText: '知道了',
      onOk() { },
      maskClosable: true
    });
  }
  const [isShowRemarkReplyUpdate, setIsShowRemarkReplyUpdate] = useState<boolean>(false)
  //备注修改变化
  function remarkReplUpdateChange(ev: ChangeEvent<HTMLTextAreaElement>, id: number) {
    const value = ev.target.value
    const updates = remarkReplyUpdates.map(ele => {
      return { ...ele, content: ele.id === id ? value : ele.content }
    })
    setRemarkReplyUpdates(updates)
  }
  //点击修改备注
  function updateRemarkReply(list: RemarkReply[] | undefined, type: number) {
    setIsShowRemarkReplyUpdate(true)
    //过滤出备注信息列表
    let remarkReplys: RemarkReply[] = []

    if (list) {
      remarkReplys = list.filter(ele => ele.type === type)
    }
    //转化成展示的dom
    let updates: RemarkReplyUpdate[] = remarkReplys.map((ele: RemarkReply) => {
      return {
        id: ele.id, title: ele.time, content: ele.content
      }
    })
    setRemarkReplyUpdates(updates)
  }
  const [remarkReplyUpdates, setRemarkReplyUpdates] = useState<RemarkReplyUpdate[]>([])
  //修改备注信息
  function remarkReplyUpdateClick(id: number, content: string) {
    //校验数据
    if (!(id > 0)) {
      message.error({
        content: "数据出现错误，请稍后再试！"
      })
    }
    if (!content) {
      message.warning({ content: "备注信息不能为空" })
    }
    let params = new URLSearchParams()
    params.append("id", `${id}`)
    params.append("content", content)
    updateRemarkInfo(params).then(res => {
      const code = res.status
      if (code === 200) {
        message.success({ content: res.data })
        //修改成功后，更新一下，资源列表备注信息
        const sources = source.map(ele => {
          return {
            ...ele, remarkReplys: ele.remarkReplys?.map(el => {
              return { ...el, content: el.id === id ? content : el.content }
            })
          }
        })
        setSource(sources)
      }
    }).catch((error: AxiosError<string>) => {
      message.error({ content: error.response?.data })
    })
  }
  //点击删除备注
  function remarkReplyRemoveClick(id: number) {
    if (!(id > 0)) {
      message.error({
        content: "数据出现错误，请稍后再试！"
      })
    }
    let params = new URLSearchParams()
    params.append("id", `${id}`)
    removeRemarkInfo(params).then(res => {
      const code = res.status
      if (code === 200) {
        message.success({ content: res.data })
        //删除成功后处理备注信息和资源列表
        const updates = remarkReplyUpdates.filter(ele => !(ele.id === id))
        setRemarkReplyUpdates(updates)
        const sources = source.map(ele => {
          return {
            ...ele, remarkReplys: function () {
              const updates = ele.remarkReplys?.filter(el => !(el.id === id))
              return updates
            }()
          }
        })
        setSource(sources)
      }
    }).catch((error: AxiosError<string>) => {
      message.error({ content: error.response?.data })
    })
  }


  //修改是否发送权限
  function switchChange(checked: boolean, id: number, type: number) {
    let params = new URLSearchParams()
    params.append("id", `${id}`)
    params.append("status", `${checked ? 0 : 1}`)
    params.append("type", `${type}`)
    updateSendStatus(params).then(res => {
      const code = res.status
      if (code === 200) {
        message.success({ content: res.data })
        //更新列表数据
        const sources = source.map(ele => {
          if (type === 0) {
            return { ...ele, is_phone_send: id === ele.id ? (checked ? 0 : 1) : ele.is_phone_send }
          } else {
            return { ...ele, is_email_send: id === ele.id ? (checked ? 0 : 1) : ele.is_email_send }
          }
        })
        setSource(sources)
      }
    }).catch((error: AxiosError<string>) => {
      message.error({ content: error.response?.data })
    })
  }
  const columns: TableProps<Resource>['columns'] = [
    {
      title: 'id',
      dataIndex: 'id',
    },
    {
      title: '公司名称',
      width: 250,
      dataIndex: "company"
    },
    {
      title: '法定代表人',
      dataIndex: "corp_name"
    },
    {
      title: '电话',
      dataIndex: 'phone'
    },
    {
      title: '邮箱',
      dataIndex: 'email'
    },
    {
      title: '统计',
      render(_, record) {
        return <>
          <StatVessel>
            <StatusDesc>电话沟通次数：</StatusDesc>
            <StatText>{record.link_up}</StatText>
          </StatVessel>
          <StatVessel>
            <StatusDesc>短链点击次数：</StatusDesc>
            <StatText>{record.click_count}</StatText>
          </StatVessel>
          <StatVessel>
            <StatusDesc>短信发送次数：</StatusDesc>
            <StatText>{record.phone_send}</StatText>
          </StatVessel>
          <StatVessel>
            <StatusDesc>邮箱发送次数：</StatusDesc>
            <StatText>{record.email_send}</StatText>
          </StatVessel>
        </>
      },
    },
    {
      title: '状态',
      render(_, record) {
        return <>
          <StatusVessel>
            <StatusDesc>是否经营异常：</StatusDesc>
            <StatusDescInfo color={record.is_exception === 0 ? "red" : "#52c41a"}>{record.is_exception === 0 ? "异常" : "正常"}</StatusDescInfo>
          </StatusVessel>
          <StatusVessel>
            <StatusDesc>是否电话沟通过：</StatusDesc>
            <StatusDescInfo color={record.is_link_up === 0 ? "#CFD1D5" : "#52c41a"}>{record.is_link_up === 0 ? "未沟通" : "沟通过"}</StatusDescInfo>
          </StatusVessel>
          <StatusVessel>
            <StatusDesc>是否能发短信：</StatusDesc>
            <Switch checkedChildren="开启" unCheckedChildren="关闭"
              checked={record.is_phone_send === 0 ? true : false}
              onChange={(ev) => switchChange(ev, record.id, 0)} />
          </StatusVessel>
          <StatusVessel>
            <StatusDesc>是否能发邮箱：</StatusDesc>
            <Switch onChange={(ev) => switchChange(ev, record.id, 1)} checkedChildren="开启" unCheckedChildren="关闭" checked={record.is_email_send === 0 ? true : false} />
          </StatusVessel>
        </>
      },
    },
    {
      title: '备注/回复',
      render(_, record, index) {
        return <>
          <StatusVessel>
            <StatusDesc>沟通备注：</StatusDesc>
            <RemarkReplyHandleVessel color="#1677FF" onClick={() => queryRemarkReplys(record.remarkReplys, 0)}>查看</RemarkReplyHandleVessel>
            <RemarkReplyHandleVessel color="#FFB416" onClick={() => updateRemarkReply(record.remarkReplys, 0)}>修改</RemarkReplyHandleVessel>
            <RemarkReplyHandleVessel color="#39FF16" onClick={() => addRemark(record.id)}>添加</RemarkReplyHandleVessel>
          </StatusVessel>
          <StatusVessel>
            <StatusDesc>短信回复：</StatusDesc>
            <RemarkReplyHandleVessel color="#1677FF" onClick={() => queryRemarkReplys(record.remarkReplys, 1)}>查看</RemarkReplyHandleVessel>
          </StatusVessel>
        </>
      },
    },
    {
      title: '链接/短链',
      render(_, record) {
        return <StatVessel>
          {
            record.link ? <Tooltip title={record.link}>
              <PaperClipOutlined style={{
                fontSize: 17,
                marginRight: 7,
                color: '#1677FF'
              }} />
            </Tooltip> : ""
          }
          {record.short_link}
        </StatVessel>
      },
    }
  ];

  const screens: Screen[] = [
    {
      label: "全部",
      value: -1
    },
    {
      label: "电话沟通过",
      value: 0
    },
    {
      label: "电话未沟通过",
      value: 1
    },
    {
      label: "能短信发送",
      value: 2
    },
    {
      label: "不能短信发送",
      value: 3
    },
    {
      label: "能邮箱发送",
      value: 4
    },
    {
      label: "不能邮箱发送",
      value: 5
    },
    {
      label: "异常公司",
      value: 6
    },
    {
      label: "正常公司",
      value: 7
    }
  ]

  const [screen, setScreen] = useState<number>(-1)
  function screenChange(ev: number) {
    setScreen(ev)
  }

  function fileCange(ev: ChangeEvent<HTMLInputElement>) {
    let files = ev.target.files//获取第一个文件
    if (files?.length && files.length > 0) {
      let file = files[0]
      let reader = new FileReader()
      reader.readAsBinaryString(file)//读取这个文件
      reader.onload = function (event: ProgressEvent<FileReader>) {
        try {
          const target = event.target
          if (target) {
            let result = target.result
            let xlsxdata = XLSX.read(result, { type: 'binary' })//读取xlsx
            for (let n in xlsxdata.Sheets) {//这里是多张表格 所以写一个循环
              let col = XLSX.utils.sheet_to_json<string[]>(xlsxdata.Sheets[n], { header: 1, defval: '', blankrows: true })//解析为数组
              let basics: ResourceBody[] = []
              col?.forEach((ele, index) => {
                const company = ele[0]
                const corp_name = ele[1]
                const phone = `${ele[2]}`
                const email = ele[3]
                if (company && corp_name && phone) {
                  let source: ResourceBody = {
                    company: company,
                    corp_name: corp_name,
                    phone: phone
                  }
                  if (email) { source = { ...source, email: email } }
                  basics.push(source)
                }
              })
              if (basics.length >= 1) {
                //上传请求数据
                uploadRouce(basics).then(res => {
                  const code = res.status
                  if (code !== 200) {
                    const msg = res.data
                    message.error({ content: msg })
                  } else {
                    const data: Blob = res.data
                    if (data.size > 0) {
                      fileExport(data, 'application/vnd.ms-excel;charset=utf-8', "资源重复数据.xlsx")
                      message.warning({ content: "数据存在重复，已导入文件中" })
                    } else {
                      message.success({ content: "导入数据成功" })
                    }
                  }
                })
              }
            }
          }
        } catch (err) {
          message.error({
            content: '读取Excel失败:' + err
          })
        }
      }
    }

  }

  function fileClick(ev: MouseEvent<HTMLInputElement>) {
    (ev.target as HTMLInputElement).value = ""
  }

  function fileExport(data: Blob, type: string, name: string): void {
    // 文件类型
    let blob = new Blob([data], { type: type })
    // 创建下载链接
    let url = window.URL.createObjectURL(blob)
    // 赋值给a标签的href属性
    let aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = url
    aLink.setAttribute('download', name)
    // 将a标签挂载上去
    document.body.appendChild(aLink)
    // a标签click事件
    aLink.click()
    // 移除a标签
    document.body.removeChild(aLink)
    // 销毁下载链接
    window.URL.revokeObjectURL(url)
  }


  const [companyName, setCompanyName] = useState<string>()
  //公司名称change
  function companyChange(ev: ChangeEvent<HTMLInputElement>) {
    const value = ev.target.value
    setCompanyName(value)
  }
  const [phone, setPhone] = useState<string>()
  //电话号码change
  function phoneChange(ev: ChangeEvent<HTMLInputElement>) {
    const value = ev.target.value
    setPhone(value)
  }
  const [corpName, setCorpName] = useState<string>()
  //法人名称change
  function corpNameChange(ev: ChangeEvent<HTMLInputElement>) {
    const value = ev.target.value
    setCorpName(value)
  }

  const [current, setCurrent] = useState<number>(1)
  const [size] = useState<number>(15)
  //点击查询
  function inquire(page: number) {
    setCurrent(page)
    let param: ResourceParam = {
      current: page,
      size: size,
      screen: screen
    }
    if (companyName) {
      param = { ...param, company: companyName }
    }
    if (phone) {
      param = { ...param, phone: phone }
    }
    if (corpName) {
      param = { ...param, corpName: corpName }
    }
    resouceQuery(param).then(res => {
      const result = res.data
      setSource(result.resources)
      setTotal(result.total)
    })
  }


  const [showAddDrawer, setShowAddDrawer] = useState<boolean>(false)

  const [addCompany, setAddCompany] = useState<string>()
  function addCompanyChange(ev: ChangeEvent<HTMLTextAreaElement>) {
    setAddCompany(ev.target.value)
  }
  const [party, setParty] = useState<string>()
  function partyChange(ev: ChangeEvent<HTMLInputElement>) {
    setParty(ev.target.value)
  }

  const [addPhone, setAddPhone] = useState<string>()
  function addPhoneChange(ev: ChangeEvent<HTMLInputElement>) {
    setAddPhone(ev.target.value)
  }

  const [addEmail, setAddEmail] = useState<string>()
  function addEmailChange(ev: ChangeEvent<HTMLInputElement>) {
    setAddEmail(ev.target.value)
  }

  //点击提交信息
  function addSubmit() {
    //校验数据
    let params = new URLSearchParams()
    if (!addCompany) {
      return message.error({
        content: "公司名称必填！"
      })
    }
    if (!party) {
      return message.error({
        content: "法人名称必填！"
      })
    }

    if (!addPhone) {
      return message.error({
        content: "联系电话必填！"
      })
    }

    params.append("company", addCompany)
    params.append("corp_name", party)
    params.append("phone", addPhone)
    if (addEmail) {
      params.append("email", addEmail)
    }

    resouceAdd(params).then(res => {
      const code = res.status
      if (code === 200) {
        setShowAddDrawer(false)
        message.success({ content: res.data })
        //清空数据
        setAddCompany("")
        setAddPhone("")
        setParty("")
        setAddEmail("")
      }
    }).catch((error: AxiosError<string>) => {
      message.error({ content: error.response?.data })
    })

  }


  //点击短信批量发送
  function smsBacthSend(size: number) {
    bacthSendSms(size).then(res => {
      const code = res.status
      if (code === 200) {
        message.success({ content: res.data })
      }
    })
  }

  const [addRemarkId, setAddRemarkId] = useState<number>()
  const [addRemarkMsg, setAddRemarkMsg] = useState<string>()
  //点击提交备注信息
  function remarkAddSubmit() {
    //校验数据信息
    if (!addRemarkId) {
      return message.error({
        content: "数据出现异常，请稍后再试！"
      })
    }
    if (!addRemarkMsg) {
      return message.error({
        content: "请填写备注信息"
      })
    }
    let params = new URLSearchParams()
    params.append("id", `${addRemarkId}`)
    params.append("content", addRemarkMsg)
    addRemarkInfo(params).then(res => {
      const code = res.status
      if (code === 200) {
        message.success({ content: "添加备注成功" })
        setAddRemarkMsg("")
        setIsShowAddRemark(false)
      }
    })
  }
  //添加备注信息输入框发生变化
  function addRemarkChange(ev: ChangeEvent<HTMLTextAreaElement>) {
    setAddRemarkMsg(ev.target.value)
  }

  //点击页数发生变化
  function paginationChange(page: number) {
    inquire(page)
  }

  //是否显示设置发送条数
  const [isShowSettingNum, setIsShowSettingNum] = useState<boolean>(false)
  //设置默认条数
  const [settingSendNum, setSettingSendNum] = useState<number>(1000)
  //发送条数发生改变
  function settingSendNumChange(ev: ChangeEvent<HTMLInputElement>) {
    setSettingSendNum(Number(ev.target.value))
  }
  //点击提交批量发送短信
  function settingNumSubmit() {
    //判断是否发送条数大于0
    if (settingSendNum > 0) {
      smsBacthSend(settingSendNum)
      setIsShowSettingNum(false)
    } else {
      message.error({ content: "发送条数必须大于0" })
    }
  }
  return <Vessel>
    <TitleVessel>
      <h2>资源管理</h2>
      <TitleHandle>
        <Button style={{ marginRight: 10, letterSpacing: 2 }} onClick={() => setIsShowSettingNum(true)}>短信批量</Button>
        <Button style={{ marginRight: 10, letterSpacing: 2 }} onClick={() => message.warning({ content: "功能暂未开放" })}>邮箱批量</Button>
        <Button style={{ marginRight: 10, letterSpacing: 2 }} onClick={() => setShowAddDrawer(true)}>添加</Button>
        <Button icon={<ToTopOutlined />} style={{ marginRight: 10, position: 'relative', letterSpacing: 2 }}>
          <FileInput
            type='file'
            accept='application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            onClick={fileClick}
            onChange={fileCange}
          />
          导入
        </Button>
      </TitleHandle>
    </TitleVessel>
    <TitleVessel style={{ paddingBottom: 10 }}>
      <TitleHandle>
        <Input placeholder="请输入公司名称"
          style={{ width: 200, marginRight: 15, marginBottom: 5 }}
          value={companyName}
          onChange={companyChange}
          allowClear />
        <Input placeholder="请输入手机号"
          type="number"
          style={{ width: 150, marginRight: 15, marginBottom: 5 }}
          allowClear
          maxLength={11}
          minLength={11}
          value={phone}
          onChange={phoneChange} />
        <Input placeholder="请输入法人名称"
          style={{ width: 150, marginRight: 15, marginBottom: 5 }}
          allowClear
          value={corpName}
          onChange={corpNameChange} />
        <Select
          value={screen}
          style={{ width: 150, marginBottom: 5 }}
          onChange={screenChange}
          options={screens}
        />
      </TitleHandle>
      <Button type="primary" onClick={() => inquire(1)}>查询</Button>
    </TitleVessel>
    <Table dataSource={source}
      columns={columns}
      rowKey={(res) => res.id}
      pagination={{
        current: current,
        pageSize: size,
        total: total,
        showSizeChanger: false,
        onChange: paginationChange
      }} />


    <Drawer open={showAddDrawer}
      title="添加资源"
      onClose={() => setShowAddDrawer(false)}>
      <ResouceAddVessel>
        <ResouceAddWhiteSpace style={{ alignItems: 'flex-start' }}>
          <ResouceAddHandleTitle style={{ marginTop: 5 }}>公司名称：&emsp;</ResouceAddHandleTitle>
          <TextArea rows={4} value={addCompany} onChange={addCompanyChange} />
        </ResouceAddWhiteSpace>
        <ResouceAddWhiteSpace>
          <ResouceAddHandleTitle>法定代表人：</ResouceAddHandleTitle>
          <Input value={party} onChange={partyChange} />
        </ResouceAddWhiteSpace>
        <ResouceAddWhiteSpace>
          <ResouceAddHandleTitle>联系电话：&emsp;</ResouceAddHandleTitle>
          <Input maxLength={11} minLength={11} value={addPhone} onChange={addPhoneChange} type="number" />
        </ResouceAddWhiteSpace>
        <ResouceAddWhiteSpace>
          <ResouceAddHandleTitle>电子邮箱：&emsp;</ResouceAddHandleTitle>
          <Input value={addEmail} onChange={addEmailChange} />
        </ResouceAddWhiteSpace>
        <Button type='primary' style={{ marginTop: 25, float: 'right' }} onClick={addSubmit}>提交</Button>
      </ResouceAddVessel>
    </Drawer>


    <Drawer
      title="修改沟通备注信息"
      open={isShowRemarkReplyUpdate}
      onClose={() => setIsShowRemarkReplyUpdate(false)}>
      <Steps
        progressDot
        direction="vertical"
        items={remarkReplyUpdates.map(ele => {
          return {
            ...ele, description: <RemarkReplyUpdateVessel>
              <TextArea rows={3} style={{ width: 200 }} value={ele.content}
                onChange={(ev) => remarkReplUpdateChange(ev, ele.id)}
              ></TextArea>
              <CheckOutlined style={{ color: '#1677FF', fontSize: 20, marginLeft: 15, marginTop: 5 }} onClick={() => remarkReplyUpdateClick(ele.id, ele.content)} />
              <MinusOutlined style={{ color: 'red', fontSize: 20, marginLeft: 15, marginTop: 5 }} onClick={() => remarkReplyRemoveClick(ele.id)} />
            </RemarkReplyUpdateVessel>
          }
        })}
        current={remarkReplyUpdates.length}
      />
    </Drawer>

    <Modal
      title="添加沟通备注"
      okText="提交"
      cancelText="取消"
      open={isShowAddRemark}
      onCancel={() => setIsShowAddRemark(false)}
      onOk={remarkAddSubmit}
      width={400}
    >
      <TextArea rows={5} value={addRemarkMsg} onChange={addRemarkChange}></TextArea>
    </Modal>


    <Modal
      title="设置发送条数"
      okText="提交"
      cancelText="取消"
      open={isShowSettingNum}
      onCancel={() => setIsShowSettingNum(false)}
      onOk={settingNumSubmit}
      width={400}
    >
      <Input placeholder="请输入发送条数"
        value={settingSendNum}
        onChange={settingSendNumChange}
        type="number"
        allowClear />
    </Modal>

  </Vessel>
}

export type {
  Resource,
  ResourceBody,
  RemarkReply
}

export default Resouce